

// 将websocket封装成单例模式
let socket = null;

export const connectWebSocket = (url) =>{

    if(!socket){
        // 创建websocket对象
        socket = new WebSocket(url);

        // 创建连接
        socket.onopen = () =>{
            console.log("websocket连接成功");
        }

        // 监听消息
        socket.onmessage = (event) =>{
            // console.log("收到消息：",event.data);

            // 收到消息
            socket.send("收到消息："+event.data);
        }

        // 关闭连接
        socket.onclose = () =>{
            console.log("websocket连接关闭");
        }

        socket.onerror = () =>{
            console.log("websocket连接错误");
        }

        return socket;
    }
}

export const getWebSocket = () =>{
    return socket;
}

export const closeWebSocket = () =>{
    if(socket){
        socket.close();
        socket = null;
    }
}



